package com.travel.travelnetwork.util;

import com.travel.travelnetwork.bean.Log;
import org.apache.catalina.User;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@Component
@Aspect
public class LogAop {
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private final static Logger logger= LoggerFactory.getLogger(LogAop.class);

    @Pointcut("execution(* com.travel.travelnetwork.controller.back.*.*(..))")
    public void pointCut(){

    }
    @Before("pointCut()")
    public void doBefore(JoinPoint joinPoint){
        Date date = new Date();
        request.setAttribute("visitTime", date);
    }

    @After("pointCut()")
    public void doAfter(){
        Log log = new Log();


        Date visitTime = (Date) request.getAttribute("visitTime");
        Date now = new Date();
        int executionTime=(int)(now.getTime()-visitTime.getTime());//访问时长
        String ip = request.getRemoteAddr();//访问IP
        String requestURL = request.getRequestURI();//访问路径
        //取user对象
        Object user = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if(user instanceof User){
            String username = ((User) user).getUsername();
            log.setUsername(username);
        }
        log.setIp(ip);
        log.setExecutionTime(executionTime);
        log.setUrl(requestURL);
        log.setVisitTime(visitTime);
        logger.info(log.toString());

    }
    @AfterThrowing(pointcut = "pointCut()",throwing = "ex")
    public void afterThrowing(Throwable ex){
        Log log = new Log();


        Date visitTime = (Date) request.getAttribute("visitTime");
        Date now = new Date();
        int executionTime=(int)(now.getTime()-visitTime.getTime());//访问时长
        String ip = request.getRemoteAddr();//访问IP
        String requestURL = request.getRequestURI();//访问路径
        //取user对象
        Object user = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if(user instanceof User){
            String username = ((User) user).getUsername();
            log.setUsername(username);
        }
        log.setIp(ip);
        log.setExecutionTime(executionTime);
        log.setUrl(requestURL);
        log.setVisitTime(visitTime);
        //异常信息
        String exMessage = ex.getMessage();
        log.setExceptionMessage(exMessage);

        logger.info(log.toString());

    }
}
